#!/usr/bin/env node

const mysql = require('mysql2/promise'),
      log   = console.log,
      Koa   = require('koa'),
      app   = new Koa(),
      Router = require('koa-router'),
      router = new Router(),
      mime  = require('mime-types'),
      fs    = require('fs'),
      path  = require('path'),
      cors  = require('koa2-cors'),
      http  = require('http'),
      https = require('https');

const options = {
    key:fs.readFileSync(path.join(__dirname,'./fourgoldhua.cn.key')),
    cert:fs.readFileSync(path.join(__dirname,'./fourgoldhua.cn.crt'))
}

app.use(cors({
    origin: function (ctx) {
      if (ctx.url === '/shuju') {
        return "*"; // 允许来自所有域名请求
      }
      return 'http://localhost:8080'; // 这样就能只允许 http://localhost:8080 这个域名的请求了
    },
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST', 'DELETE'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}))

router.get('/shuju/shouye',async (ctx) => {
  let arr = await getShouye();
  log(arr);
  ctx.body = JSON.stringify(arr);
})

router.get('/shuju/ss',async (ctx) =>{
  let {user_id,text} = ctx.request.query;
  let arr = await getshouyess(user_id,text);
  for(let i=0;i<arr.length;i++){
    if(arr[i].state ==null) arr[i].state = '2'; 
  }
  log(arr);
  ctx.body = JSON.stringify(arr);
})

async function getshouyess(id,text){
    const sql = 
  `select main_table.share_id,main_table.user_id,user_name,user_img,title,img1,size,state from main_table left join user_table on main_table.user_id=user_table.id left join img_table on main_table.share_id = img_table.id left join concern_collect_table on main_table.share_id=concern_collect_table.share_id where main_table.title like '%${text}%' or main_table.text like '%${text}%' or main_table.addr like '%${text}%' or main_table.food like '%${text}%'and main_table.judge!=2 and concern_collect_table.user_id = '${id}' order by share_id desc`;
    let [rows] = await con.execute(sql);
    return rows;
}
 

router.get('/shuju/api',async (ctx,next) => {
    let arr = await getAreas();
    ctx.body = JSON.stringify(arr);
    await next();
})

router.get('/shuju/fenlei',async (ctx) => {
  let {food,addr} = ctx.request.query;
  let arr;
  if(food!=null) arr = await getfenlei(food);
  else if(addr!=null) arr = await getfenlei1(addr);
  ctx.body = JSON.stringify(arr);
})

router.get('/shuju/state',async (ctx)=>{
  let {user_id,food,addr} = ctx.request.query;
  let arr;
  if(food!=null) arr= await getcollect(food);
  else if(addr!=null) arr=await getcollect1(addr);
  for(let i = 0;i<arr.length;i++){
      if(arr[i].user_id!=user_id){  
            arr[i].user_id=null;
            arr[i].state='2';
          }
  }
  for(let i = 0;i < arr.length-1 ;i++){
      if(arr[i].share_id == arr[i+1].share_id){
            if(arr[i].user_id == user_id) arr.splice(i+1,1);
            else arr.splice(i,1);
          }
  }
  log(arr);
  ctx.body = JSON.stringify(arr);
})


router.get('/shuju/del',async (ctx) => {
  let {share_id} = ctx.request.query;
  let arr = await delid_main(share_id); 
  ctx.body = JSON.stringify(arr);
})


//请求首页数据
async function getShouye(){
    const sql = 
	`select share_id,main_table.user_id,user_name,user_img,title,img1,size from main_table,user_table,img_table where main_table.judge!=2 and main_table.user_id = user_table.id and main_table.share_id = img_table.id and judge != 2 order by share_id desc`;
    let [rows] = await con.execute(sql);
    return rows;
}
//分类数据
async function getfenlei(food){
    const sql = 
  `select share_id,main_table.user_id,user_name,user_img,title,img1,size from main_table,user_table,img_table where main_table.judge!=2 and main_table.user_id = user_table.id and main_table.share_id = img_table.id and  main_table.food = '${food}' order by share_id desc`;
    let [rows] = await con.execute(sql);
    return rows;
}

async function getfenlei1(addr){
    const sql = 
  `select share_id,main_table.user_id,user_name,user_img,title,img1,size from main_table,user_table,img_table where main_table.judge!=2 and main_table.user_id = user_table.id and main_table.share_id = img_table.id and  main_table.addr = '${addr}' order by share_id desc`;
    let [rows] = await con.execute(sql);
    return rows;
}

//删除数据
async function delid_main(id){
    const sql =`delete from main_table where share_id = ${id}`;
    let [rows] = await con.execute(sql);
    return rows;
}

async function getcollect(food){
    const sql =`select main_table.share_id,concern_collect_table.user_id,concern_collect_table.state from main_table left join concern_collect_table on concern_collect_table.share_id = main_table.share_id where main_table.food = '${food}' order by share_id desc`;
    let [rows] = await con.execute(sql);
    return rows;
}

async function getcollect1(addr){
    const sql =`select main_table.share_id,concern_collect_table.user_id,concern_collect_table.state from main_table left join concern_collect_table on concern_collect_table.share_id = main_table.share_id where main_table.addr = '${addr}' order by share_id desc`;
    let [rows] = await con.execute(sql);
    return rows;
}

router.get('/shuju/sx',async (ctx) => {
  let arr = await get_id(12);
  let obj = new Object();
  obj.data = parseInt(arr[0].shop_username);
  console.log(obj);
  ctx.body = JSON.stringify(obj);
})

async function get_id(id){
  const sql = `select * from Merchants_settled_table where id = ${id}`;
  let [rows] = await con.execute(sql);
  return rows;
}

let con = mysql.createPool({
    host:'154.8.156.240',
    port:'2020',
    user:'root',
    password:'Ljj0222.',
    database:'tuijian'
});

getAreas();

process.on('unhandledRejection',(reason,p) => {
    console.log('Unhandled Rejection at:Promise',p,'reason:',reason);
});

async function getAreas(){
    const sql = 
	'select share_id,shop_id,title,text,date,addr,user_name,user_img,food,tags,img1,img2,img3,img4 from main_table left join user_table on user_table.id = main_table.user_id left join img_table on img_table.id = main_table.share_id where user_table.id = 2020001';
    let [rows] = await con.execute(sql);
    return rows;
}

//(async function(){
//    log(await getAreas());
//})();

app.use(router.routes())
   .use(router.allowedMethods());

https.createServer(options,app.callback()).listen(3333);
